package postgres

import (
	"context"
	"manager/model"
	"manager/model/entity"
	"manager/utils"
)

// TrackStatics 骑行统计
func (a *routeList) TrackStatics(ctx context.Context, in *model.CyclingStaticsReq) (rsp *model.CyclingStaticsRsp, err error) {
	rsp = &model.CyclingStaticsRsp{}
	// 统计一段时间内的数据
	_db := GetDB(ctx).Model(entity.RouteList{})

	// 过滤用户车辆ID
	if in.UserId > 0 {
		_db.Where("user_id = ?", in.UserId)
	}

	if err = _db.Where("ebike_id = ?", in.EbikeId).Error; err != nil {
		return
	}
	// 过滤时间

	if in.StartTime > 0 && in.EndTime > 0 {
		if err = _db.Where("start_time >= ? and end_time < ?", in.StartTime, in.EndTime).Error; err != nil {
			return
		}
	}

	var list []entity.RouteList
	if err = _db.Scan(&list).Error; err != nil {
		return
	}

	/*	if in.EndTime-in.StartTime > 60*24*3600 {
		err = errors.New("search time span more than 60 days")
		return
	}*/

	// 每日里程统计
	daysMileageMap := map[string]int{}

	// 时间跨度
	avgSpeedCount := 0
	for i := 0; i < len(list); i++ {
		// 累计里程
		rsp.AccumulatedMileage += list[i].Mileage
		// 最高时速
		if rsp.MaxSpeed < list[i].MaxSpeed {
			rsp.MaxSpeed = list[i].MaxSpeed
		}
		// 平均时速
		avgSpeedCount += list[i].AvgSpeed
		// 骑行次数
		rsp.CyclingCount++
		// 每日里程统计
		timeUnix := utils.NowDayUnix(list[i].CreatedAt)
		daysMileageMap[utils.DayUnixToFormat(timeUnix)] += list[i].Mileage
	}

	rsp.MileageStatics = make([]*model.MileageOfDay, 0)
	for k, v := range daysMileageMap {
		rsp.MileageStatics = append(rsp.MileageStatics, &model.MileageOfDay{
			Day:     k,
			Mileage: v,
		})
	}

	// 平均骑行时速
	if rsp.CyclingCount > 0 {
		rsp.AvgSpeed = avgSpeedCount / rsp.CyclingCount
	}

	return
}
